package com.sxkeda.voip;

import java.util.List;

import org.linphone.LinphoneActivity;
import org.linphone.LinphoneManager;
import org.linphone.LinphonePreferences;
import org.linphone.LinphoneService;
import org.linphone.LinphoneUtils;
import org.linphone.R;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCallParams;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneCall.State;
import org.linphone.core.LinphoneCore.RegistrationState;
import org.linphone.mediastream.Log;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

public class CallApi
{
	private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 201;
	private static final int PERMISSIONS_REQUEST_RECORD_AUDIO_INCOMING_CALL = 203;
	private static final int PERMISSIONS_REQUEST_CAMERA = 205;
	private static Debug debug = new Debug(Debug.isKedaCallApi, "KedaCallApi");
	private static LinphoneCall mCall;

	public static void hangUp()
	{
		LinphoneCore lc = LinphoneManager.getLc();
		LinphoneCall currentCall = lc.getCurrentCall();

		debug.i("lc.isInConference() = " + lc.isInConference());

		if (currentCall != null)
		{
			debug.i("terminateCall(currentCall)");
			lc.terminateCall(currentCall);
		}
		else if (lc.isInConference())
		{
			debug.i("terminateConference");
			lc.terminateConference();
		}
		else
		{
			debug.i("terminateAllCalls");
			lc.terminateAllCalls();
		}
	}

	public static void dialNumber(String number)
	{
		if (LinphoneManager.getLc().getCallsNb() == 0)
		{
			debug.i("dialNumber(" + number + ");");
			LinphoneManager.getInstance().newOutgoingCall(number, number);
		}
	}

	public static void answer(Context mContext)
	{

		if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null)
		{
			List<LinphoneCall> calls = LinphoneUtils.getLinphoneCalls(LinphoneManager.getLc());
			for (LinphoneCall call : calls)
			{
				if (State.IncomingReceived == call.getState())
				{
					mCall = call;
					break;
				}
			}
		}

		if (State.IncomingReceived != mCall.getState()) return;

		if (mContext.getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED || LinphonePreferences.instance()
		        .audioPermAsked())
		{
			// startActivity(new Intent(LinphoneActivity.instance(),
			// CallIncomingActivity.class));
			debug.i("CallIncomingActivity.class");
		}
		else
		{
			debug.i("checkAndRequestAudioPermission(true);");
			checkAndRequestAudioPermission(mContext, true);
		}

		LinphoneCallParams params = LinphoneManager.getLc().createCallParams(mCall);

		boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext());

		if (params != null)
		{
			params.enableLowBandwidth(isLowBandwidthConnection);
		}
		else
		{
			Log.e("Could not create call params for call");
		}

		if (params == null || !LinphoneManager.getInstance().acceptCallWithParams(mCall, params))
		{
			// the above method takes care of Samsung Galaxy S
			// Toast.makeText(this, R.string.couldnt_accept_call,
			// Toast.LENGTH_LONG).show();
		}
		else
		{
			// if (!LinphoneActivity.isInstanciated()) {
			// return;
			// }
			final LinphoneCallParams remoteParams = mCall.getRemoteParams();
			if (remoteParams != null && remoteParams.getVideoEnabled() && LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests())
			{
				// LinphoneActivity.instance().startVideoActivity(mCall);
				debug.i("LinphoneActivity.instance().startVideoActivity(mCall)");
				switchVideo(true);
			}
			else
			{
				debug.i("LinphoneActivity.instance().startIncallActivity(mCall);");
				// LinphoneActivity.instance().startIncallActivity(mCall);
				switchVideo(false);
			}
		}
	}

	private static void switchVideo(final boolean displayVideo)
	{
		debug.i("switchVideo");
		final LinphoneCall call = LinphoneManager.getLc().getCurrentCall();
		if (call == null)
		{
			return;
		}

		// Check if the call is not terminated
		if (call.getState() == State.CallEnd || call.getState() == State.CallReleased) return;

		if (!displayVideo)
		{
			// showAudioView();
		}
		else
		{
			if (!call.getRemoteParams().isLowBandwidthEnabled())
			{
				LinphoneManager.getInstance().addVideo();
				debug.i("addVideo");
				// if (videoCallFragment == null ||
				// !videoCallFragment.isVisible())
				// {
				// showVideoView();
				// }
			}
			else
			{
				// displayCustomToast(getString(R.string.error_low_bandwidth),
				// Toast.LENGTH_LONG);
			}
		}
	}

	public static void checkAndRequestAudioPermission(Context mContext, boolean isIncomingCall)
	{
		if (LinphonePreferences.instance().audioPermAsked())
		{
			return;
		}
		checkAndRequestPermission(mContext, Manifest.permission.RECORD_AUDIO, isIncomingCall ? PERMISSIONS_REQUEST_RECORD_AUDIO_INCOMING_CALL : PERMISSIONS_REQUEST_RECORD_AUDIO);
		if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests())
		{
			checkAndRequestCameraPermission(mContext);
		}
	}

	public static void checkAndRequestPermission(Context mContext, String permission, int result)
	{
		if (mContext.getPackageManager().checkPermission(permission, mContext.getPackageName()) != PackageManager.PERMISSION_GRANTED)
		{
			// ActivityCompat.requestPermissions(com.sxkeda.voip.ui.KedaUiMain.class,
			// new String[]{ permission }, result);
		}
	}

	public static void checkAndRequestCameraPermission(Context mContext)
	{
		if (LinphonePreferences.instance().cameraPermAsked())
		{
			return;
		}
		checkAndRequestPermission(mContext, Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA);
	}
/*
	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
	{
		// TODO Auto-generated method stub
		debug.i("onRequestPermissionsResult");
		if (grantResults.length > 0)
		{
			for (int i = 0; i < grantResults.length; i++)
			{
				if (grantResults[i] == PackageManager.PERMISSION_DENIED)
				{
					// if
					// (!ActivityCompat.shouldShowRequestPermissionRationale(this,
					// permissions[i])) {
					// if
					// (permissions[i].equals(Manifest.permission.RECORD_AUDIO))
					// {
					// LinphonePreferences.instance().neverAskAudioPerm();
					// } else if
					// (permissions[i].equals(Manifest.permission.CAMERA)) {
					// LinphonePreferences.instance().neverAskCameraPerm();
					// } else if
					// (permissions[i].equals(Manifest.permission.READ_CONTACTS))
					// {
					// LinphonePreferences.instance().neverAskReadContactsPerm();
					// } else if
					// (permissions[i].equals(Manifest.permission.WRITE_CONTACTS))
					// {
					// LinphonePreferences.instance().neverAskWriteContactsPerm();
					// } else if
					// (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE))
					// {
					// LinphonePreferences.instance().neverAskWriteExternalStoragePerm();
					// }
					// } else {
					// //TODO: show dialog explaining what we need the
					// permission for
					// }
					// } else {
					if (permissions[i].equals(Manifest.permission.RECORD_AUDIO))
					{
						LinphonePreferences.instance().neverAskAudioPerm();
					}
					else if (permissions[i].equals(Manifest.permission.CAMERA))
					{
						LinphonePreferences.instance().neverAskCameraPerm();
					}
					else if (permissions[i].equals(Manifest.permission.READ_CONTACTS))
					{
						LinphonePreferences.instance().neverAskReadContactsPerm();
					}
					else if (permissions[i].equals(Manifest.permission.WRITE_CONTACTS))
					{
						LinphonePreferences.instance().neverAskWriteContactsPerm();
					}
					else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE))
					{
						LinphonePreferences.instance().neverAskWriteExternalStoragePerm();
					}
				}
			}
		}
		switch(requestCode)
		{
		case PERMISSIONS_REQUEST_RECORD_AUDIO:
			debug.i("PERMISSIONS_REQUEST_RECORD_AUDIO");
			// startActivity(new Intent(this, CallOutgoingActivity.class));
			break;
		case PERMISSIONS_REQUEST_RECORD_AUDIO_INCOMING_CALL:
			debug.i("PERMISSIONS_REQUEST_RECORD_AUDIO_INCOMING_CALL");
			// startActivity(new Intent(this, CallIncomingActivity.class));
			break;
		}
	}
*/
}
